﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Net.Mail;

public partial class Grocery : System.Web.UI.Page
{

    string facebook_urlAuthorize_base = "https://graph.facebook.com/oauth/authorize";
    string facebook_urlGetToken_base = "https://graph.facebook.com/oauth/access_token";
    string facebook_AppID = "208238106017076";
    string facebook_AppSecret = "f0a6b786428b48f2c57dfbe917aef832";
    //FacebookAuthen fb = new FacebookAuthen();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Session.Remove("RecipeId");
            if (Request["code"] != null)
            {
                string authorizationCode = Request["code"];
                string access_token = Facebook_GetAccessToken(authorizationCode);
                if (access_token == "")
                {
                    Response.Write("Could not get access_token");
                    return;
                }
                Facebook_WriteWall(access_token, (string)Session["Message"]);
            }
        }
    }

    protected void imgShare_Click(object sender, ImageClickEventArgs e)
    {
        Session["message"] = shareIngredient.Value;
        Facebook_AuthorizeApplication();
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        Session["RecipeId"] = "";
        
    }

    protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        try
        {
            

            //string _userName = "";
            //if (Session["UserName"] != null)
            //    _userName = "of " + Session["UserName"].ToString();
            //string _mailServer = "smtp.gmail.com";
            //int _mailPort = 587;
            //string _user = "planitmeal2013@gmail.com";
            //string _pass = "11911431121176";
            //string _mailFrom = "planitmeal2013@gmail.com";
            //string _body = "";
            //if (Check.Value.Equals("true"))
            //{
            //    _body = SendDepart.Value.Replace("+", "<br/>");
            //}
            //else
            //{
            //    _body = SendIngredient.Value.Replace("+", "<br/>");
            //}

            //MailMessage mailMessage = new MailMessage();
            //SmtpClient mailClient = new SmtpClient(_mailServer, _mailPort);
            //mailClient.Timeout = 15000;
            //mailClient.Credentials = new NetworkCredential(_user, _pass);
            //mailClient.EnableSsl = true;

            //mailMessage.IsBodyHtml = true;
            //mailMessage.From = new MailAddress(_mailFrom);
            //mailMessage.Subject = "[PlanItMeal]Grocery " + _userName;
            //mailMessage.Body = _body;

            //mailMessage.To.Add(txtEmail.Text);
            //mailClient.Send(mailMessage);
            ////att.Dispose();
            //mailMessage.Dispose();
            //SendDepart.Value = "";
            //SendIngredient.Value = "";
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "$('#dialogEmail').dialog('open');", true);
        }
        catch (Exception ex)
        {
            //ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('" + ex.Message + "!')", true);
        }
    }


    

    #region
    private void Facebook_AuthorizeApplication()
    {
        string scope = "publish_stream"; //see: http://developers.facebook.com/docs/authentication/permissions/ for extended permissions
        string urlAuthorize = facebook_urlAuthorize_base;
        urlAuthorize += "?client_id=" + facebook_AppID;
        urlAuthorize += "&redirect_uri=" + Facebook_GetRedirectUri();
        urlAuthorize += "&scope=" + scope;
        Response.Redirect(urlAuthorize, true);
    }

    private string Facebook_GetAccessToken(string pAuthorizationCode)
    {
        string urlGetAccessToken = facebook_urlGetToken_base;
        urlGetAccessToken += "?client_id=" + facebook_AppID;
        urlGetAccessToken += "&client_secret=" + facebook_AppSecret;
        urlGetAccessToken += "&redirect_uri=" + Facebook_GetRedirectUri();
        urlGetAccessToken += "&code=" + pAuthorizationCode;

        string responseData = RequestResponse(urlGetAccessToken); //we write RequestResponse a little later
        if (responseData == "")
        {
            return "";
        }
        NameValueCollection qs = HttpUtility.ParseQueryString(responseData);
        string access_token = qs["access_token"] == null ? "" : qs["access_token"];

        return access_token;
        //(The access_token is valid only from within the site domain specified for our Facebook application)
    }

    private void Facebook_WriteWall(string pAccessToken, string pMessage)
    {
        string username = "me";
        string datatype = "feed";
        string urlWriteWall = "https://graph.facebook.com/" + username + "/" + datatype + "?access_token=" + pAccessToken;

        //the message to post as a key/value pair
        string entityMessage = "message=" + Session["message"];
        entityMessage += "&picture=http://www.planitmeal.com/newdesign/images/logo.jpg";
        entityMessage += "&link=" + Facebook_GetRedirectUri();
        entityMessage += "&name=Plan It Meal";
        entityMessage += "&caption=Meal Plan this week";

        HttpPost(urlWriteWall, entityMessage); //we write HttpPost a little later
    }

    private string Facebook_GetRedirectUri()
    {
        string urlCurrentPage = Request.Url.AbsoluteUri.IndexOf('?') == -1 ? Request.Url.AbsoluteUri : Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf('?'));
        NameValueCollection nvc = new NameValueCollection();
        foreach (string key in Request.QueryString) { if (key != "code") { nvc.Add(key, Request.QueryString[key]); } }
        string qs = "";
        foreach (string key in nvc)
        {
            qs += qs == "" ? "?" : "&";
            qs += key + "=" + nvc[key];
        }
        string redirect_uri = urlCurrentPage + qs; //urlCallback have to be exactly the same each time it is used (that's why the code key is removed)

        return redirect_uri;
    }

    private string HttpPost(string pUrl, string pPostData)
    {
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(pUrl);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(pPostData);
        Stream requestWriter = webRequest.GetRequestStream(); //GetRequestStream
        requestWriter.Write(bytes, 0, bytes.Length);
        requestWriter.Close();

        Stream responseStream = null;
        StreamReader responseReader = null;
        string responseData = "";
        try
        {
            WebResponse webResponse = webRequest.GetResponse();
            responseStream = webResponse.GetResponseStream();
            responseReader = new StreamReader(responseStream);
            responseData = responseReader.ReadToEnd();
        }
        catch (Exception exc)
        {
            throw new Exception("could not post : " + exc.Message);
        }
        finally
        {
            if (responseStream != null)
            {
                responseStream.Close();
                responseReader.Close();
            }
        }

        return responseData;
    }

    private string RequestResponse(string pUrl)
    {
        HttpWebRequest webRequest = System.Net.WebRequest.Create(pUrl) as HttpWebRequest;
        webRequest.Method = "GET";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        Stream responseStream = null;
        StreamReader responseReader = null;
        string responseData = "";
        try
        {
            WebResponse webResponse = webRequest.GetResponse();
            responseStream = webResponse.GetResponseStream();
            responseReader = new StreamReader(responseStream);
            responseData = responseReader.ReadToEnd();
        }
        catch (Exception exc)
        {
            Response.Write("<br /><br />ERROR : " + exc.Message);
        }
        finally
        {
            if (responseStream != null)
            {
                responseStream.Close();
                responseReader.Close();
            }
        }

        return responseData;
    }
    #endregion
   
}